import localforage from "localforage"
import { Project } from "./Project"
import { Deserializer } from "../serialize/Deserializer"
import { Dzer } from "../serialize"


/**
 * oProject - opened Project
 * 打开的项目
 */
export const oProject = ref(null as Project | null)
export const oStorage = computed(() => oProject.value?.storage)
const STORAGEKEY_PROJECT = 'global-oProject'

export function loadProject() {
  
  localforage.getItem(STORAGEKEY_PROJECT)
    .then(val => {
      if (val) {
        if (Object.prototype.toString.call(val) === '[object String]') {
          val = JSON.parse(val as any)
        }
        const project: Project = Dzer.deserialize(val)
        console.log('加载项目', project);
        oProject.value = project

        ////////////////////////////
        //  debug out zone
        ////////////////////////////
        // console.log('有data的槽');
        // console.log(project.storage.slots.filter(x => x.data !==undefined))
        // console.log('叫名字的槽');
        // console.log(project.storage.slots.filter(x => x.prototype.name === '名字'))
        // console.log('迭代节点');
        // console.log(project.storage.nodes.filter(x => x.prototype.title === '迭代'))
      }
      else {
        oProject.value = new Project()
      }
    })
}


export const oProjectUnsave = ref(false)

watch(oProject, _ => {
  oProjectUnsave.value = true
}, { deep: true })

export function saveOProject() {
  if (!oStorage.value) {
    throw new Error('!oStorage.value')
  }
  oStorage.value.shake()
  localforage.setItem(STORAGEKEY_PROJECT, JSON.parse(JSON.stringify(oProject.value)))
    .then(() => {
      oProjectUnsave.value = false
    })
}

export function clearOProject() {

  ElMessageBox.confirm(
    '确认要清空项目？',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      oProject.value = new Project()
      saveOProject()
    })
    .catch(() => {
      
    })
}